package com.aglow.updateDownload.code;

import android.content.Intent;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.aglow.updateDownload.listener.UpdateDownloadListener;

import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Author: chufeng
 * Email: 392044178@qq.com
 * Date: 2019/1/4 10:31
 * Depict:下载管理模块
 */
public class DownloadManager {
    private ThreadPoolExecutor threadPoolExecutor;
    private static DownloadManager manager;
    private UpdateDownloadRequest request;


    public DownloadManager() {
        threadPoolExecutor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
    }

    static {
        manager = new DownloadManager();
    }

    public static DownloadManager getInstance() {
        return manager;

    }


    /**
     * 启动下载
     */
    public void startDownload(String downloadUrl, String localPath, UpdateDownloadListener listener) {

        if (request != null) {
            return;
        }
        checkLocalFilePath(localPath);
        request = new UpdateDownloadRequest(downloadUrl, localPath, listener);
        Future<?> submit = threadPoolExecutor.submit(request);
    }

    /**
     * 检查文件路径
     **/
    private void checkLocalFilePath(String path) {
        File dir = new File(path.substring(0, path.lastIndexOf("/") + 1)); //得到文件夹路径
        Log.i("download","path = "+path.substring(0, path.lastIndexOf("/") + 1));
        if (TextUtils.isEmpty(path)){
            return;
        }
        if (!dir.exists()) {
            dir.mkdir();
        }
//        File file = new File(path);
//        if (!file.exists()) {//创建文件
//            try {
//                file.createNewFile();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
    }

}
